import axios from 'axios';
import WPopView from '../utils/popView';
import { getToken } from '@/utils/auth';
import { InputChangeEvent } from '@/utils/type/global';
import store from '../store';
import router from '../router';

// 创建axios实例
const service = axios.create({
  timeout: 30000, // 请求超时时间
  // baseURL: '/yb-api'
})

// request拦截器
service.interceptors.request.use(
  (config: any) => {
    if (store.getters.token) {
      config.headers.Token = getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    console.log('================= url ==================')
    console.log(config.url);
    console.log('================= 参数 ==================')
    console.log(config.method === 'get' ? config.params : config.data);
    // 所有请求都带上 authentication
    config.headers.Authentication = store.getters.token;
    // config.headers['Access-Control-Allow-Headers'] = 'Authentication'
    return config;
  },
  (error: any) => {
    Promise.reject(error);
  },
)

// respone拦截器
service.interceptors.response.use(
  (response: any) => {
    const res = response.data;
    console.log('================= response ==================', response.config.url);
    console.log(res);
    if (res.code !== 0) {
      WPopView.msgError(res.msg ? res.msg : '网络错误');
      if (res.code === 13001 || res.code === 13002) {
        WPopView.msgError('请重新登录');
        store.dispatch('FED_LOG_OUT');
        router.push('/');
      }
      return Promise.reject(res);
    } else {
      return res.data;
    }
  },
  (error: any) => {
    WPopView.msgError(error.message);
    return Promise.reject(error);
  },
);

// 自定义封装git
export function get(url: string, params = {}) {
  return service.get(url, {
    // 请求参数
    params,
  });
}

// 自定义封装POST
export function post(url: string, params = {}) {
  return service.post(url, params);
}

// 图片上传
export function upImage(url: string, name: string, e: InputChangeEvent) {
  const file: File = e.target.files![0];
  // 判断图片大小，超出后直接返回
  const fileSize = file.size;
  if (fileSize > (2 * 1024 * 1024)) {
    return Promise.reject({
      code: 1,
      msg: '图片大小不能超所2M',
    });
  }
  // 创建form对象
  const params = new FormData();
  // 通过append向form对象添加数据
  params.append(name, file, file.name);
  return service.post(url, params, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}

// 上传文件
export function upFile(url: string, params = {}) {
  return service.post(url, params, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}
